package c_admin

import (
	"gintest/until"
	"github.com/gin-gonic/gin"
	"github.com/satori/go.uuid"
	"os"
	"path"
	"image"
	"image/jpeg"
	_"image/png"
	_"image/gif"
	"github.com/nfnt/resize"
	"strconv"
	"net/http"
)
/**
单文件上传
普通上传
*/
func Upload_index(c *gin.Context) {

	 // 单文件
	 file, _ := c.FormFile("file")

	 u2:= uuid.NewV4()
	 filename:=u2.String()+path.Ext(file.Filename)
	 // 上传文件到指定的路径
	 c.SaveUploadedFile(file, "uploads/"+filename)

	 var xy=""
	 if c.Request.TLS==nil{
	 	xy="http://"
	 }else{
	 	xy="https://"
	 }
	 //xy=c.Request.URL.Scheme
	 ePath, _ := os.Getwd()
	 until.Success(c,map[string]interface{}{
	 	"filename":filename,
	 	"url":xy+c.Request.Host+"/upload/img?n="+filename,
	 	"filesize":file.Size,
	 	"path":ePath+"/uploads/"+filename,
	 })
}
/**
编辑器上传
返回格式与普通上传不同
*/
func Upload_edit(c *gin.Context){
	// 单文件
	file, _ := c.FormFile("file")

	u2:= uuid.NewV4()
	filename:=u2.String()+path.Ext(file.Filename)
	// 上传文件到指定的路径
	c.SaveUploadedFile(file, "uploads/"+filename)

	var xy=""
	if c.Request.TLS==nil{
		xy="http://"
	}else{
		xy="https://"
	}
	//xy=c.Request.URL.Scheme
	//ePath, _ := os.Getwd()
	c.JSON(http.StatusOK,gin.H{"code":0,"msg":"","data":map[string]interface{}{"title":filename,"src":xy+c.Request.Host+"/upload/img?n="+filename}})
}
/**
* 图片展示
* http://api.gintest.com:8080/upload/img?n=8d9f9be3-04d1-4640-812f-b9d65dc2ee57.jpg&w=100&h=100
* 
*/
func Upload_img(c *gin.Context){
	filename:=c.Query("n")
	w:=c.DefaultQuery("w","0")
	h:=c.DefaultQuery("h","0")
	path := "uploads/"+filename
	outpath:=""
	if w!="0" || h!="0"{
		outpath="uploads/" + w + "_" + h + "_" + filename
		_,err:=os.Stat(outpath)//判断是否处理过该文件名
		if err != nil{
			file,err:=os.Open(path)
			if err != nil{
				until.Fail(c,1,err.Error())
				return
			}
			defer file.Close()

			img,_,err:=image.Decode(file)
			if err != nil{
				until.Fail(c,1,err.Error())
				return
			}
			wn,_:=strconv.Atoi(w)
			hn,_:=strconv.Atoi(h)
			m:=resize.Resize(uint(wn),uint(hn),img,resize.Lanczos3)

			out,err:=os.Create(outpath)
			if err != nil{
				until.Fail(c,1,err.Error())
				return
			}
			defer out.Close()
			jpeg.Encode(out,m,nil)
		}	
	}else{
		outpath=path
	}
	c.File(outpath)
}